package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.datatype.CP;
import ca.uhn.hl7v2.model.v24.group.MFN_M04_MF_CDM;
import ca.uhn.hl7v2.model.v24.message.MFK_M01;
import ca.uhn.hl7v2.model.v24.message.MFN_M04;
import ca.uhn.hl7v2.model.v24.segment.*;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Date;

public class DepositConvert extends AbstractMessageConvert {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgInHos(ProxyMsgCodeConstant.DEPOSIT);
        MFN_M04 hl7Message = (MFN_M04) requestMessage.getHl7Message();
        MFN_M04_MF_CDM mfCdm = hl7Message.getMF_CDM();
        MFE mfe = mfCdm.getMFE();
        int k = mfe.getMfe4_PrimaryKeyValueMFEReps();
        Varies[] varies = mfe.getMfe4_PrimaryKeyValueMFE();
        for(int j=0;j<k;j++){
            GenericPrimitive primitive = (GenericPrimitive) varies[j].getData();
            String[] temp = primitive.getValue().split("=");
            if (temp.length>1){
                document.getRootElement().addElement(temp[0]).addText(temp[1] != null ? temp[1] : "");
            }else {
                document.getRootElement().addElement(temp[0]).addText("");
            }
        }

        String res = document.asXML().replace("&#6;",String.valueOf((char)6));
        logger.info(requestMessage.getMsgCode()+" to HIS XML = "+ res);
        return document;
    }

    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200300 from HIS XML = "+ message);
        message = message.replace("&#x6;#","MFK_M01_MESSAGE");
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        MFK_M01 mfk = new MFK_M01();
        mfk.initQuickstart("MFK_M01", "MFK_M01", "A");
        MSH msh = mfk.getMSH();
        initResponseMessageMSH(msh);
        MSA msa = mfk.getMSA();
        msa.getErrorCondition().getCe1_Identifier().setValue(doc.getRootElement().elementTextTrim("IsSuccessed"));
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().elementTextTrim("ErrorMsg").replace("MFK_M01_MESSAGE","&#x6;#"));
        MFI mfi = mfk.getMFI();

        mfi.getMfi1_MasterFileIdentifier().getIdentifier().setValue("ReceiptNum="+doc.getRootElement().element("Data").elementTextTrim("ReceiptNum"));

        return mfk;
    }

    @Override
    public Message generatorReqMessage() throws Exception {
        MFN_M04 message = new MFN_M04();
        message.initQuickstart("MFN_M04", "MFN_M04", "A");
        MSH msh = message.getMSH();
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200080");
        msh.getMsh11_ProcessingID().getPt2_ProcessingMode().setValue(IdGenerator.getUUID());
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMsh7_DateTimeOfMessage().getTs1_TimeOfAnEvent().setValue(new Date());
        msh.getMsh10_MessageControlID().setValue(IdGenerator.getUUID());
        MFI mfi = message.getMFI();

        mfi.getMasterFileIdentifier().getIdentifier().setValue("CLINIC");
        mfi.getMfi2_MasterFileApplicationIdentifier().getHd1_NamespaceID().setValue("SSM");
        mfi.getFileLevelEventCode().setValue("REGISTER");
        mfi.getEnteredDateTime().getTs1_TimeOfAnEvent().setValue(new Date());
        mfi.getMfi5_EffectiveDateTime().getTs1_TimeOfAnEvent().setValue(new Date());
        MFN_M04_MF_CDM mfCdm = message.getMF_CDM();
        MFE mfe = mfCdm.getMFE();
        mfe.getRecordLevelEventCode().setValue("ORDER");
        mfe.getEffectiveDateTime().getTs1_TimeOfAnEvent().setValue(new Date());



        /**
         * patientId
         */
        addGenericPrimitive(mfe, "HISPatientID","40021810311243270555");

        /**
         *身份证号
         */
        addGenericPrimitive(mfe,"IDCardNo", "331081199507027314");

        /**
         * 医保卡卡号
         */
        addGenericPrimitive(mfe,"MedCardNo", "6217250200034095643");

        /**
         * 医保卡密码
         */

        addGenericPrimitive(mfe,"MedCardPwd", "111111");


        /**
         * 监护人身份证号
         */

        addGenericPrimitive(mfe,"GIDCardNo", "331081199507027314");


        /**
         * 结算类型
         */

        addGenericPrimitive(mfe,"InsureTypeCode", "1");

        /**
         * 门特类型
         */

        addGenericPrimitive(mfe,"MtTypeCode", "");

        /**
         * visitCode 其他业务接口返回的值
         */

        addGenericPrimitive(mfe,"VisitCode", "000013|2018-11-06|P");

        /**
         * VisitDate 就诊日期
         */

        addGenericPrimitive(mfe,"VisitDate", "2018-11-06");

        /**
         * VisitTypeCode 号别编号
         */

        addGenericPrimitive(mfe,"VisitTypeCode", "000013");

        /**
         * AppointCode 预约编号
         */
        addGenericPrimitive(mfe,"AppointCode", "");
        /**
         * PatientName 患者姓名
         */
        addGenericPrimitive(mfe,"PatientName", "陈统");

        /**
         * PatientAge 患者年龄
         */
        addGenericPrimitive(mfe,"PatientAge", "23");
        /**
         * PatientBirthday 出生年月日
         */
        addGenericPrimitive(mfe,"PatientBirthday", "1995-07-02");
        /**
         * PatientSex 生别 1男 2女
         */
        addGenericPrimitive(mfe,"PatientSex", "1");


        /**
         * DivisionID 医保分割id
         */
        addGenericPrimitive(mfe,"DivisionID", "");

        /**
         * BusinessFrom 业务来源 * 1手机 2网站  3自助机  4窗口 5电话
         */
        addGenericPrimitive(mfe,"BusinessFrom", "3");

        /**
         * 费用说明
         */
        CDM cdm = mfCdm.getCDM();
        cdm.getPrimaryKeyValueCDM().getCe1_Identifier().setValue("CLINIC");
        cdm.getPrimaryKeyValueCDM().getText().setValue("挂号");
        cdm.getChargeDescriptionShort().setValue("挂号");
        cdm.getActiveInactiveFlag().setValue("A");
        /**
         * 订单信息说明
         */
        PRC prc = mfCdm.getPRC();
        prc.getPrc1_PrimaryKeyValuePRC().getCe1_Identifier().setValue("CLINIC");
        prc.getPrc1_PrimaryKeyValuePRC().getText().setValue("挂号费");

        /**
         * 订单附属信息 科室、医生
         */
        CE department = prc.getDepartment(0);
        /**
         * 设置科室代码
         */
        department.getCe1_Identifier().setValue("01010202");
        /**
         * 设置医生代码
         */
        department.getText().setValue("");
        /**
         * 金额信息
         */
        CP cp = prc.getPrice(0);
        cp.getCp1_Price().getQuantity().setValue("1");
        cp.getCp1_Price().getMo2_Denomination().setValue("20.00");
        cp.getCp2_PriceType().setValue("RMB");
        prc.getEffectiveEndDate().getTs1_TimeOfAnEvent().setValue(new Date());
        /**
         * 上下午、晚上标志 A上午P下午W晚上Q全天
         */
        prc.getPrc2_FacilityIDPRC(0).getCe1_Identifier().setValue("001775,@20181126@1");
        prc.getPrc2_FacilityIDPRC(1).getCe1_Identifier().setValue("1|成功|120102197006091191|吴辉|48|1|天津医科大学中新生态城医院|21000683310|1|191#");
        prc.getActiveInactiveFlag().setValue("P");
        prc.getCost().getQuantity().setValue("1");
        prc.getCost().getMo2_Denomination().setValue("20.00");
        return message;
    }




    private String getGenericPrimitiveValue(Varies varies) throws Exception {
        GenericPrimitive primitive = (GenericPrimitive) varies.getData();
        if (primitive != null) {
            String res = primitive.getValue();
            return res != null ? res : "";
        } else {
            return "";
        }
    }
}
